package com.xms.security.api.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.xms.core.exception.XmsException;
import com.xms.dependency.XmsDependencyException;
import com.xms.security.api.model.CreatePrivilegeModel;
import com.xms.security.api.model.UpdatePrivilegeModel;
import com.xms.security.entity.Privilege;
import com.xms.security.service.sitemap.*;
import com.xms.utils.CollectionUtil;
import com.xms.utils.StringUtil;
import com.xms.utils.UUIDUtil;
import com.xms.web.framework.controller.ApiBaseController;
import com.xms.web.framework.model.DeleteManyModel;
import com.xms.web.framework.model.JsonResultObject;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.sql.SQLException;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.UUID;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author migo
 * @since 2021-08-29
 */
@RestController
@RequestMapping("/{org}/api/security/privilege")
public class PrivilegeController extends ApiBaseController {
    private IPrivilegeFinderService _privilegeFinderService;
    private IPrivilegeCreaterService _privilegeCreaterService;
    private IPrivilegeUpdaterService _privilegeUpdaterService;
    private IPrivilegeDeleterService _privilegeDeleterService;
    private IPrivilegeTreeBuilder _privilegeTreeBuilder;
    @Autowired
    public PrivilegeController(IPrivilegeFinderService privilegeFinderService,
                               IPrivilegeCreaterService privilegeCreaterService,
                               IPrivilegeUpdaterService privilegeUpdaterService,
                               IPrivilegeDeleterService privilegeDeleterService,
                               IPrivilegeTreeBuilder privilegeTreeBuilder){
        _privilegeFinderService = privilegeFinderService;
        _privilegeCreaterService = privilegeCreaterService;
        _privilegeUpdaterService = privilegeUpdaterService;
        _privilegeTreeBuilder = privilegeTreeBuilder;
        _privilegeDeleterService = privilegeDeleterService;
    }

    @ApiOperation("查询菜单")
    @GetMapping("list")
    public JsonResultObject list(@RequestParam(value="authorizationenabled", required = false) Boolean authorizationenabled){
        LambdaQueryWrapper<Privilege> queryWrapper = new LambdaQueryWrapper<>();
        if(authorizationenabled != null) {
            queryWrapper.eq(Privilege::getAuthorizationenabled, authorizationenabled);
        }
        queryWrapper.orderByAsc(Privilege::getDisplayorder);
        return JOk(_privilegeFinderService.list(queryWrapper));
    }

    @ApiOperation("查询菜单")
    @GetMapping("getbyid/{id}")
    public JsonResultObject getById(@PathVariable(value = "id", required = true) UUID id) {
        Privilege entity = _privilegeFinderService.getById(id);
        if (entity == null) {
            return JNotFound();
        }
        return JOk(entity);
    }

    @ApiOperation("查询菜单")
    @GetMapping("getbyids/{id}")
    public JsonResultObject getByIds(@PathVariable(value = "id", required = true) String id) {
        if(StringUtil.isEmpty(id)){
            return JNotSpecifiedParams("id");
        }
        String[] idArr = StringUtil.splitSafe(id, ",");
        List<UUID> ids = new ArrayList<>();
        for (String a : idArr){
            ids.add(UUIDUtil.get(a));
        }

        return JOk(_privilegeFinderService.getByIds(ids));
    }

    @ApiOperation("查询菜单树结构")
    @GetMapping("tree")
    public String tree() {
        String result = _privilegeTreeBuilder.build(null);
        return result;
    }

    @ApiOperation("菜单排序")
    @GetMapping("move")
    public JsonResultObject move(@RequestParam(value="moveid", required = true) UUID moveid,
                                 @RequestParam(value="targetid", required = true) UUID targetid,
                                 @RequestParam(value="parentid", required = true) UUID parentid,
                                 @RequestParam(value="position", required = true) String position) {
        boolean success = _privilegeUpdaterService.move(moveid, targetid, parentid, position);
        return success ? JOk() : JUpdateFailure();
    }

    @ApiOperation("新增菜单")
    @PostMapping("create")
    public JsonResultObject create(@RequestBody CreatePrivilegeModel model) throws XmsException, SQLException {
        Privilege entity = new Privilege();
        entity.setPrivilegeid(UUIDUtil.get());
        entity.setParentprivilegeid(model.parentprivilegeid);
        entity.setUrl(model.url);
        entity.setAuthorizationenabled(model.authorizationenabled);
        entity.setBigicon(model.bigicon);
        entity.setSmallicon(model.smallicon);
        entity.setSystemname(model.systemname);
        entity.setClassname(model.classname);
        entity.setMethodname(model.methodname);
        entity.setDescription(model.description);
        entity.setDisplayname(model.displayname);
        entity.setDisplayorder(model.displayorder);
        entity.setOpentarget(model.opentarget);
        entity.setIsvisibled(model.isvisibled);
        entity.setCreatedon(LocalDateTime.now());
        entity.setOrganizationid(_currentUser.getUser().OrganizationId);
        boolean success = _privilegeCreaterService.create(entity);
        return success ? JCreateSuccess() : JCreateFailure();
    }

    @ApiOperation("修改菜单")
    @PostMapping("update")
    public JsonResultObject update(@RequestBody UpdatePrivilegeModel model) throws XmsException, SQLException {
        if(UUIDUtil.isEmpty(model.privilegeid)){
            return JNotSpecifiedParams("privilegeid");
        }
        Privilege entity = _privilegeFinderService.getById(model.privilegeid);
        entity.setUrl(model.url);
        entity.setAuthorizationenabled(model.authorizationenabled);
        entity.setBigicon(model.bigicon);
        entity.setSmallicon(model.smallicon);
        entity.setSystemname(model.systemname);
        entity.setClassname(model.classname);
        entity.setMethodname(model.methodname);
        entity.setDescription(model.description);
        entity.setDisplayname(model.displayname);
        entity.setDisplayorder(model.displayorder);
        entity.setOpentarget(model.opentarget);
        entity.setIsvisibled(model.isvisibled);
        boolean success = _privilegeUpdaterService.update(entity);
        return success ? JUpdateSuccess() : JUpdateFailure();
    }


    @ApiOperation("删除菜单")
    @PostMapping("deletebyid")
    public JsonResultObject deleteById(@RequestBody DeleteManyModel model) throws SQLException, XmsDependencyException {
        if(CollectionUtil.isEmpty(model.RecordId)){
            return JNotSpecifiedParams("id");
        }
        if(_privilegeDeleterService.deleteByIds(Arrays.asList(model.RecordId))){
            return JDeleteSuccess();
        }
        return JDeleteFailure();
    }
}
